<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>

    // "YYYY-MM-DD hh:mm:ss"
    // 2022-10-24 16:18:20
    // 2022-10-24 16:18
    // 2022-10-24
    // 16:18:20


    // 日期格式化
    // pattern 传入的模板 => 期望输出的格式
    function dateFormat(pattern, inputTime) { // "YYYY-MM-DD hh:mm:ss"

        if (pattern == undefined) pattern = "YYYY-MM-DD hh:mm:ss";

        if (inputTime == undefined) {
            var date = new Date();
        } else {
            var date = new Date(inputTime);
        }

        var year = date.getFullYear();
        var month = date.getMonth() + 1;  //展示到页面中
        var day = date.getDate();

        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();

        return pattern.replace("YYYY", year).replace("MM", beauty(month)).replace("DD", beauty(day)).replace("hh", beauty(hour)).replace("mm", beauty(minute)).replace("ss", beauty(second))
    }


    function beauty(num) {
        return num < 10 ? "0" + num : num;
    }


    console.log(dateFormat("YYYY-MM-DD hh:mm:ss"));
    console.log(dateFormat("YYYY-MM-DD hh:mm"));
    console.log(dateFormat("YYYY-MM-DD"));
    console.log(dateFormat("hh:mm:ss"));

    var date = new Date("2022/10/9 12:34:56")
    console.log(dateFormat("YYYY-MM-DD hh:mm:ss", date));
    console.log(dateFormat("YYYY/MM/DD hh:mm:ss", date));
</script>

</html>